import store from 'store'

import { history } from '@umijs/max'
import type { RunTimeLayoutConfig } from '@umijs/max'

import { layoutConfig } from '@/layout'
import api from '@/services'

const { userCurrent } = api

// 初始化应用时调用
export async function onRouteChange({ location, routes, action }: any) {
  const { pathname } = location

  // 如果访问的是登录页或404页面，不进行权限检查
  if (pathname === '/login' || pathname === '/404') {
    return
  }

  let isLogin = false
  try {
    const res = await userCurrent()
    if (res.code === 200) {
      store.set('current_user', res.data)
      isLogin = true
    } else {
      store.clearAll()
    }
  } catch (error) {
    store.clearAll()
  }

  if (!isLogin) {
    // 跳转到登录页，并携带当前页面作为返回地址
    history.push({
      pathname: '/login',
      search: `from=${pathname}`,
    })
  }
}

export const layout: RunTimeLayoutConfig = () => {
  return {
    ...layoutConfig,
  }
}

// 禁止 findDOMNode 警告
const originalWarn = console.warn
console.warn = function (...args) {
  if (typeof args[0] === 'string' && args[0].includes('findDOMNode is deprecated')) {
    return // 忽略该警告
  }
  originalWarn.apply(console, args)
}
